package com.balance.anole.erp.navigate.adapter;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.balance.anole.erp.Activator;
import com.balance.anole.erp.navigate.model.MenuNode;
import com.balance.anole.erp.navigate.model.MenuNodeType;

public class AdapterFactory implements IAdapterFactory {

	private IWorkbenchAdapter nonLeafAdapter = new IWorkbenchAdapter() {
		public Object getParent(Object o) {
			return ((MenuNode) o).getParent();
		}

		public String getLabel(Object o) {
			MenuNode group = ((MenuNode) o);
			 return group.getName() +
			      " (" + group.getChildren().size() + ")";

		}

		public ImageDescriptor getImageDescriptor(Object object) {
			return AbstractUIPlugin.imageDescriptorFromPlugin(
					Activator.PLUGIN_ID, ISharedImages.IMG_OBJ_ELEMENT);
		}

		public Object[] getChildren(Object o) {
			return ((MenuNode) o).getChildren().toArray();
		}
	};

	private IWorkbenchAdapter leafAdapter = new IWorkbenchAdapter() {
		public Object getParent(Object o) {
			return ((MenuNode) o).getParent();
		}

		public String getLabel(Object o) {
			MenuNode entry = ((MenuNode) o);
			return entry.getName() ;
		}

		public ImageDescriptor getImageDescriptor(Object object) {
			  return AbstractUIPlugin.imageDescriptorFromPlugin(
					  Activator.PLUGIN_ID, ISharedImages.IMG_OBJ_ELEMENT);
		}

		public Object[] getChildren(Object o) {
			return new Object[0];
		}
	};

	public Object getAdapter(Object adaptableObject, Class adapterType) {
		if (adapterType == IWorkbenchAdapter.class
				&& adaptableObject instanceof MenuNode && !MenuNodeType.LEAF.equalsIgnoreCase(((MenuNode)adaptableObject).getType()))
			return nonLeafAdapter;
		if (adapterType == IWorkbenchAdapter.class
				&& adaptableObject instanceof MenuNode && MenuNodeType.LEAF.equalsIgnoreCase(((MenuNode)adaptableObject).getType()))
			return leafAdapter;
		return null;
	}

	public Class[] getAdapterList() {
		return new Class[] { IWorkbenchAdapter.class };
	}
}
